#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/4/15 15:42
# @Author  : Chenmm
# @File    : SysDept.py
# @Software: PyCharm

from app import db
from datetime import datetime


class SysDept(db.Model):
    __tablename__ = 'sys_dept'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='主键')
    name = db.Column(db.String(100), nullable=False, comment='部门名称')
    code = db.Column(db.String(100), nullable=False, comment='部门编号')
    parent_id = db.Column(db.BigInteger, default=0, comment='父节点id')
    tree_path = db.Column(db.String(255), nullable=False, comment='父节点ID路径')
    sort = db.Column(db.SmallInteger, default=0, comment='显示顺序')
    status = db.Column(db.SmallInteger, default=1, comment='状态(1-正常 0-禁用)')
    create_by = db.Column(db.BigInteger, comment='创建人ID')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_by = db.Column(db.BigInteger, comment='修改人ID')
    update_time = db.Column(db.DateTime, onupdate=datetime.now, comment='更新时间')
    is_deleted = db.Column(db.SmallInteger, default=0, comment='逻辑删除标识')

    __table_args__ = (
        db.UniqueConstraint('code', name='uk_code'),
        {'comment': '部门表'}
    )


    def __init__(self, **kwargs):
        super(SysDept, self).__init__(**kwargs)
        if self.parent_id:
            self.tree_path = SysDept.query.filter_by(id=self.parent_id).first().tree_path + ',' + self.parent_id
        else:
            self.tree_path = '0'

    def to_option_json(self):
        option = {
            'value': self.id,
            'label': self.name,

            'children': [dept.to_option_json() for dept in SysDept.query.filter_by(parent_id=self.id).all()]
        }

        if not option['children']:
            del option['children']

        return option



